$(function () {
    obj.init();
});

window.obj = new function () {
    return {
        dataGrid: null,
        params: {
            schoolId: null,
            userType: 4
        },
        authTchs: [],
        init: function () {
            window.top.swal.resetDefaults();
            this.params.schoolId = xhTool.getQuery('iSchoolId');
            this.dataGrid = new xhDataGrid($('#list'), 'School/getUser', {schoolId: this.params.schoolId, userType: this.params.userType});
            this.dataGrid.parseToolbar().init().activeButton(
                ['bt_list_set_pwd', 'bt_list_refresh_login',  'bt_list_user_group','bt_list_returnTab'],
                ['bt_list_app_group', 'bt_list_assist', 'bt_list_manage', 'bt_list_setName', 'bt_list_login']
            );
            this.funObj().bindDataGridEvent();

            xhTool.bindDocKeyDown($('#bt_list_search'));

            // $('#bt_list_spare').menubutton({
            //     menu: '#menu_spare'
            // });
            $('#bt_list_tablet').menubutton({
                menu: '#menu_tablet'
            });
            $('#bt_list_status').menubutton({
                menu: '#menu_status'
            });
            $('#bt_list_more').menubutton({
                menu: '#menu_more'
            });
            $('#bt_account_use').menubutton({
                menu: '#menu_use_type'
            });
            $('#bt_set').menubutton({
                menu: '#menu_set'
            });
            $('#bt_list_apply').menubutton({
                menu: '#menu_apply'
            });

            this.listener();
        },
        listener: function () {
            var $this = this;
            //绑定搜索事件
            $('#bt_list_search').click(function(){
                $this.funObj().search();
            });
            //刷新登陆
            $('#bt_list_refresh_login').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().refreshLogin();
            });
            //查看应用组
            // $('#bt_list_app_group').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().viewAppGroup();
            // });
            //修改密码
            $('#bt_list_set_pwd').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().setUserPwd();
            });
            //设备归还
            $('#bt_list_returnTab').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().returnTab();
            });
            //归还备用机
            // $('#bt_list_return_spare').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().doneSpareUsed();
            // });
            // //使用备用机
            // $('#bt_list_set_spare').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().openSpareList();
            // });
            // //设为历史
            // $('#bt_list_set_history').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().setHistory(true);
            // });
            // //设为正常
            // $('#bt_list_set_normal').click(function () {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().setHistory(false);
            // });
            //导出
            $('#bt_list_export').click(function () {
                // location.href = baseUrl + 'School/exportUserTablet?' + xhTool.parseParam($.extend({}, $this.funObj().search(true), $this.params));
                $this.funObj().exportTablet();
                // location.href = baseUrl + 'School/exportUserTablet?' + xhTool.parseParam($.extend({}, $this.funObj().search(true), $this.params));
            });
            //设置用户组
            $('#bt_list_user_group').click(function() {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().openUserGroup();
            });
            //远程协助
            // $('#bt_list_assist').click(function() {
            //     if(xhExtra.buttonDisabled($(this))) return false;
            //     $this.funObj().startAssist();
            // });
            //导入
            $('#bt_list_import').click(function () {
                $this.funObj().importTeacher();
            });
            //教师管理后台
            $('#bt_list_manage').click(function() {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().openTchManagePage();
            });
            //修改姓名
            $('#bt_list_setName').click(function() {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().setUserName();
            });
            //扫码登陆
            $('#bt_list_login').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().scanLogin();
            });
        },
        funObj: function () {
            var $this = this;
            return {
                search: function (_return) {
                    var params = {
                        search: {
                            vague: xhExtra.getValue($('#list_vague')),
                            items: xhExtra.getValue($('#list_items'))
                        },
                        history: xhExtra.getValue($('#list_history'))
                    };
                    if (_return) {
                        params.userIds = $this.dataGrid.getSelectValues('iUserId');
                    }
                    $this.dataGrid.reload(params);
                    if (_return) {
                        return params;
                    }
                },
                bindDataGridEvent: function () {
                    $this.dataGrid.rowStyler = function(rowIndex, rowData){
                        if (rowData.bDisable === '是'){
                            return 'background-color:yellow;';
                        }
                    };
                    $this.dataGrid.onLoadSuccess = function (data) {
                        $this.authTchs = [];
                        xhExtra.checkError(data);
                        $this.dataGrid.clear();
                    };
                    // xhExtra.clearLoadSuccess($this.dataGrid);
                    $this.dataGrid.onDblClickRow = function(rowIndex, rowData) {
                        window.top.xhTop.createNewTab('教师信息', baseUrl + 'Tch/TchTab/' + rowData.iUserId, true);
                    }
                },
                refreshLogin: function () {
                    xhExtra.ajaxRequest('School/refreshLoginInfo', {userIds: $this.dataGrid.getSelectValues('iUserId')}, {success: true, table: $this.dataGrid});
                },
                viewAppGroup: function () {
                    window.top.xhTop.createNewTab(
                        '应用组-' + $this.dataGrid.getSelectValue('sUserName'),
                        baseUrl + 'Appgroup/appGroup?' + xhTool.parseParam({schoolId: $this.params.schoolId, userId: $this.dataGrid.getSelectValue('iUserId')}),
                        true
                    );
                },
                setUserPwd: function () {
                    window.top.swal({
                        showCancelButton: true,
                        confirmButtonText: '修改',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        title: '输入新密码',
                        html: '<input type="password" id="new_pwd" class="swal2-input" placeholder="新密码" />' +
                        '<input type="password" id="confirm_pwd" class="swal2-input" placeholder="确认密码" >',
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var newPwd     = $('#new_pwd', window.top.document).val(),
                                    confirmPwd = $('#confirm_pwd', window.top.document).val();
                                if(newPwd.length < 6){
                                    reject('密码需大于6位数！');
                                } else if (newPwd !== confirmPwd) {
                                    reject('密码不匹配！');
                                } else {
                                    xhExtra.ajaxRequest('User/setPassword', {userIds: $this.dataGrid.getSelectValues('iUserId'), password: newPwd}, {success: true});
                                    resolve();
                                }
                            })
                        }
                    })
                },
                doneSpareUsed: function () {
                    var ids = xhTool.clearNullArr($this.dataGrid.getSelectValues('iUTId'));
                    if (ids.length < 1) {
                        window.top.xhTop.showError('无备用机使用！');
                        return false;
                    }
                    xhExtra.askChangeStatus(
                        'Device/doneRegister',
                        {ids: ids},
                        $this.dataGrid,
                        '归还备用机？'
                    );
                },
                openSpareList: function () {
                    var row = $this.dataGrid.getSelectValue(true);
                    if (!row) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    if (row.iUTId) {
                        window.top.xhTop.showError('已使用备用机！', '请归还后重试！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '使用备用机-' + row.sUserName,
                        size: 'lg',
                        button: '确认',
                        content: xhTool.getFrameString('Device/spareRegister', {logonName: row.sLogonName}, 500)
                    });
                },
                setHistory: function (history) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    xhExtra.askChangeStatus('User/setHistory', {ids: ids, history: history}, $this.dataGrid, history ? '设置为历史？' : '设置为正常？');
                },
                openUserGroup: function () {
                    var userIds = $this.dataGrid.getSelectValues('iUserId');
                    window.top.xhTop.showModal({
                        title: '设置用户组(共' + userIds.length + '人)',
                        button: '确认',
                        content: xhTool.getFrameString('Group/userGroup', {type: 3, userIds: userIds.join(',')}, 500)
                    });
                },
                startAssist: function () {
                    window.top.xhTop.createNewTab($this.dataGrid.getSelectValue('sUserName') + '-客户端列表', baseUrl + 'assist/users/clients?id=' + $this.dataGrid.getSelectValue('iUserId'));
                },
                importTeacher: function () {
                    window.top.swal.setDefaults({
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        progressSteps: ['1', '2']
                    });
                    window.top.swal.queue([
                        {
                            title: '导入excel文件',
                            showCancelButton: true,
                            cancelButtonText: '取消',
                            showLoaderOnConfirm: true,
                            allowOutsideClick: true,
                            input: 'file',
                            inputAttributes: {accept: '.xls,.xlsx'},
                            confirmButtonText: '导入',
                            preConfirm: function(file) {
                                return new Promise(function (resolve, reject) {
                                    if (!file) {
                                        reject('文件不能为空！');
                                    } else {
                                        resolve();
                                    }
                                })
                            }
                        },
                        {
                            text: '账号用途',
                            input: 'select',
                            inputOptions: {
                                1: '正式',
                                2: '测试',
                                3: '体验',
                                4: '临时',
                                5: '培训',
                            },
                            confirmButtonText: '确认',
                            showCancelButton: false
                        }
                    ]).then(function(result) {
                        // console.log(result);
                        // window.top.swal.resetDefaults();
                        // var fileData = new FormData();
                        // fileData.append('file', result[0]);
                        // fileData.append('autoClass', result[1]);
                        // fileData.append('type', result[2]);
                        // fileData.append('schoolId', $this.params.schoolId);
                        // $.ajax({
                        //     url: baseUrl + 'School/importStudent',
                        //     type: 'POST',
                        //     processData: false,
                        //     contentType: false,
                        //     data: fileData,
                        //     complete: function(XMLHttpRequest){
                        //         var result = XMLHttpRequest.responseJSON;
                        //         if(xhExtra.checkError(result)) return false;
                        //         window.top.xhTop.showSuccess(result.msg);
                        //         $this.dataGrid.reload();
                        //     }
                        // });
                        var fileData = new FormData();
                        fileData.append('file', result[0]);
                        fileData.append('type', result[1]);
                        fileData.append('schoolId', $this.params.schoolId);
                        $.ajax({
                            url: baseUrl + 'School/importTeacher',
                            type: 'POST',
                            processData: false,
                            contentType: false,
                            data: fileData,
                            complete: function(XMLHttpRequest){
                                var result = XMLHttpRequest.responseJSON;
                                if(xhExtra.checkError(result)) return false;
                                window.top.xhTop.showSuccess(result.msg);
                                $this.dataGrid.reload();
                            }
                        });
                    }, function(dismiss) {window.top.swal.resetDefaults();});
                    // window.top.swal({
                    //     title: '导入excel文件',
                    //     showCancelButton: true,
                    //     cancelButtonText: '取消',
                    //     showLoaderOnConfirm: true,
                    //     allowOutsideClick: true,
                    //     input: 'file',
                    //     inputAttributes: {accept: '.xls,.xlsx'},
                    //     confirmButtonText: '导入',
                    //     preConfirm: function(file) {
                    //         return new Promise(function (resolve, reject) {
                    //             if (!file) {
                    //                 reject('文件不能为空！');
                    //             } else {
                    //                 var fileData = new FormData();
                    //                 fileData.append('file', file);
                    //                 fileData.append('schoolId', $this.params.schoolId);
                    //                 $.ajax({
                    //                     url: baseUrl + 'School/importTeacher',
                    //                     type: 'POST',
                    //                     processData: false,
                    //                     contentType: false,
                    //                     data: fileData,
                    //                     complete: function(XMLHttpRequest){
                    //                         var result = XMLHttpRequest.responseJSON;
                    //                         if(xhExtra.checkError(result)) return false;
                    //                         window.top.xhTop.showSuccess(result.msg);
                    //                         $this.dataGrid.reload();
                    //                     }
                    //                 });
                    //             }
                    //         })
                    //     }
                    // });
                },
                openTchManagePage: function () {
                    var id = $this.dataGrid.getSelectValue('iUserId');
                    window.open('/school/schoolManage?schoolId=' + $this.params.schoolId + '&tchId=' + id);
                    // window.top.xhTop.createNewTab(
                    //     '教师管理-' + $this.dataGrid.getSelectValue('sUserName'),
                    //     'school/schoolManage?schoolId=' + $this.params.schoolId + 'tchId=' + id
                    // );
                },
                returnTab:function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    xhExtra.ajaxRequest('device/ajaxGetPlanName',{schoolId:$this.params.schoolId},{},function (res) {
                        var html = '';
                        html = '<select id="iBPPId" class="form-control">\n' +
                            '                  <option value=""   style="display: none;">请选择一个流程计划</option>\n';
                        if (res.length > 0) {
                            $.each(res, function (index,item) {
                                html += '      <option value="'+item['id']+'" ';
                                html +='>'+item['name']+'</option>\n' ;
                            });
                        }
                        html +='      </select>';
                        window.top.swal({
                            titleText: '退还申请',
                            html:html + '<br><textarea type="date" class="form-control" id="mDesc" rows="3"></textarea>',
                            showCancelButton: true,
                            cancelButtonText: '取消',
                            confirmButtonText: '确认',
                            showLoaderOnConfirm: true,
                            preConfirm: function () {
                                return new Promise(function (resolve, reject) {
                                    var desc = $('#mDesc' , window.top.document).val();
                                    var iBPPId = $('#iBPPId',window.top.document).val();
                                    if (!desc || !iBPPId) {
                                        reject('理由必填和流程计划必选');
                                    } else {
                                        resolve(desc);
                                    }
                                })
                            },
                            allowOutsideClick: true
                        }).then(function (desc) {
                            var iBPPId = $('#iBPPId',window.top.document).val();
                            xhExtra.ajaxRequest('device/saveReturnTab',{sSourceIds:ids.join(','),mDesc:desc,iSource:3,iBPPId:iBPPId,iSchoolId:$this.params.schoolId},null,function (res) {
                                window.top.xhTop.showSuccess(res.msg);
                                $this.dataGrid.reload();
                            });
                        }, function(dismiss) {});
                    });

                },
                setUserName: function () {
                    var userId = $this.dataGrid.getSelectValue('iUserId');
                    if (!userId) {
                        window.top.xhTop.showError('请选中教师！');
                        return false;
                    }
                    window.top.swal({
                        title: '修改姓名-' + $this.dataGrid.getSelectValue('sUserName'),
                        input: 'text',
                        inputPlaceholder: '姓名',
                        showConfirmButton: true,
                        confirmButtonText: '修改',
                        showCancelButton: true,
                        showLoaderOnConfirm: true,
                        cancelButtonText: '取消',
                        preConfirm: function (name) {
                            return new Promise(function (resolve, reject) {
                                if (!name) {
                                    reject('姓名不能为空');
                                }
                                xhExtra.ajaxRequest('school/setUserName', {userId: userId, name: name}, {success: true, check: true, table: $this.dataGrid});
                            })
                        }
                    }).then(function (name) {
                    }, function (dismiss) {});
                },
                scanLogin: function () {
                    var userId = $this.dataGrid.getSelectValue('iUserId');
                    xhExtra.ajaxRequest('School/getLoginQR', {userId: userId}, {check: true}, function(result) {
                        window.top.swal({
                            title: '登陆-' + $this.dataGrid.getSelectValue('sUserName'),
                            html: '<img src="' + result.msg + '" width="80%">',
                            showConfirmButton: true,
                            confirmButtonText: '确认'
                        }).then(function () {}, function (dismiss) {});
                    });
                },
                authTablet: function () {
                    $.extend($this.authTchs, $this.dataGrid.command('getSelections'));
                    $this.funObj().showAuthQR();
                },
                showAuthQR: function () {
                    if ($this.authTchs.length <= 0) {
                        return false;
                    }
                    var showBtn = $this.authTchs.length > 1,
                        userId  = $this.authTchs[0].iUserId,
                        userName= $this.authTchs[0].sUserName;
                    $this.authTchs.splice(0, 1);
                    xhExtra.ajaxRequest('School/userAuthQR', {userId: userId, userType: 4}, {check: false}, function(result) {
                        window.top.swal({
                            title: '认证-' + userName,
                            // html: result.error || '<img src="data:image/png;base64,' + result.msg + '" width="80%">',
                            html: result.error || '<img src="' + result.msg + '" width="80%">',
                            showConfirmButton: showBtn,
                            showCancelButton: true,
                            confirmButtonText: '下一个',
                            cancelButtonText: '关闭'
                        }).then(function () {
                            $this.funObj().showAuthQR();
                        }, function (dismiss) {});
                    });
                },
                exportTablet: function () {
                    window.top.swal({
                        title: '请选择导出类型',
                        text: '',
                        type: 'info',
                        showCancelButton: true,
                        confirmButtonText: '签收表',
                        cancelButtonText: 'MAC地址'
                    }).then(function() {
                        location.href = baseUrl + 'School/exportUserTablet?' + xhTool.parseParam($.extend({}, $this.funObj().search(true), $this.params));
                    }, function(dismiss) {
                        if (dismiss === 'cancel') {
                            location.href = baseUrl + 'School/exportUserTabletMac?' + xhTool.parseParam($.extend({}, $this.funObj().search(true), $this.params));
                        }
                    });
                },
                setRandomPwd: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    window.top.swal({
                        title: '设置随机密码-' + ids.length + '人',
                        html: '有效时长：<input type="number" id="random_hour" class="swal2-input" placeholder="默认8小时"><br />' +
                        '随机密码：<input type="password" id="random_pwd" class="swal2-input" placeholder="不填则自动生成" style="max-width: 150px;">',
                        showConfirmButton: true,
                        confirmButtonText: '确认',
                        showCancelButton: true,
                        showLoaderOnConfirm: true,
                        cancelButtonText: '取消',
                        preConfirm: function () {
                            return new Promise(function (resolve, reject) {
                                xhExtra.ajaxRequest('school/setRandomPwd', {
                                    userId: ids,
                                    hour: $('#random_hour', window.top.document).val(),
                                    pwd: $('#random_pwd', window.top.document).val()
                                }, {success: false, check: true}, function (result) {
                                    window.top.swal.close();
                                    $.fileDownload(result.msg, {
                                        failCallback: function (responseHtml, url, error) {
                                            window.top.xhTop.showError('下载失败', error);
                                        }
                                    });
                                });
                            })
                        }
                    }).then(function () {
                    }, function (dismiss) {});
                },
                cleanRandomPwd: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    xhExtra.ajaxRequest('school/cleanRandomPwd', {userId: ids}, {success: true, check: true});
                },
                useType: function (type) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中用户');
                        return false;
                    }
                    window.top.swal({
                        title: '确定要这么做吗',
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                xhExtra.ajaxRequest(
                                    'School/useType',
                                    {ids: ids, type: type,},
                                    {success: true, table: $this.dataGrid},
                                    function () {
                                        $this.classGrid.reload();
                                    }
                                );
                                resolve();
                            })
                        }
                    }).then(function(isConfirm) {}, function(dismiss) {});
                },
                setSignInData: function (type, status) {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    var arr = $('#list').datagrid('getSelections');
                    var info = [];
                    for(var i=0; i<arr.length; i++){
                        info.push({'userId': arr[i].iUserId, 'deviceNumber': arr[i].sDeviceNumber});
                    }
                    var msg = '';
                    if (type == 1 && status == 1) {
                        msg = '签收设为开启？';
                    }
                    if (type == 1 && status == 0) {
                        msg = '签收设为关闭？';
                    }
                    if (type == 2 && status == 1) {
                        msg = '协议设为开启？';
                    }if (type == 2 && status == 0) {
                        msg = '协议设为关闭？';
                    }
                    if (type == 3 && status == 1) {
                        msg = '配件设为开启？';
                    }
                    if (type == 3 && status == 0) {
                        msg = '配件设为关闭？';
                    }
                    xhExtra.askChangeStatus('School/addSignInData', {info: info, type: type, status:status}, $this.dataGrid, msg);
                },
                changeSchool: function () {
                    var ids = $this.dataGrid.getSelectValues('iUserId');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    var params = ids.join('_');
                    window.top.xhTop.showModal({
                        title:'申请转校',
                        width:330,
                        content: '<iframe src="'+baseUrl+'School/changeSchool?teacher=1&ids='+params+'"  style="width: 100%;;border-style: none;padding: 0px;height: 300px;"  scrolling="yes" ></iframe>',
                        button:'提交',
                        backClose: false
                    });
                },
            }
        }
    }
}
